/**
 * Copyright (C) 2011 Audit Logger Project. All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.auditlogger.config.providers;

import java.io.IOException;
import java.util.Properties;

import org.auditlogger.config.util.NoSuchPropertyException;

/**
 * Reads the property files that the Audit Logger uses. 
 * 
 * @author <a href="mailto:ravi.sharda@gmail.com">Ravi Sharda</a>
 */
final class PropertiesReader {
	
	private static final String STATIC_CONFIG_FILE = "configuration.properties"; 
	private static final String PLUGIN_CONFIG_FILE = "plugin.properties";
	
	private static Properties staticProps = new Properties();
	private static Properties pluginProps = new Properties();
	
	static {
		try {
			staticProps.load(PropertiesReader.class.getResourceAsStream("/" + STATIC_CONFIG_FILE));
			pluginProps.load(PropertiesReader.class.getResourceAsStream("/" + PLUGIN_CONFIG_FILE));
		} catch (IOException e) {
			throw new ExceptionInInitializerError(e);
		} 
	}
	
	public static String getValueForStaticProperty(String propertyKey) {
		return findProperty(propertyKey, STATIC_CONFIG_FILE);
	}
	
	public static String getValueForSecurityProperty(String propertyKey) {
		return findProperty(propertyKey, STATIC_CONFIG_FILE);
	}
	
	public static String getValueForPluginProperty(String propertyKey) {
		return findProperty(propertyKey, PLUGIN_CONFIG_FILE);
	}
	
	private static String findProperty(String propertyKey, String propertyFile) {
		// TODO: Read from system properties first. 
		
		Properties props = null;
		if (propertyFile == STATIC_CONFIG_FILE) {
			props = staticProps;
		} else if (propertyFile == PLUGIN_CONFIG_FILE) {
			props = pluginProps;
		} else {
			throw new IllegalArgumentException ("Invalid property file");
		}
		if (propertyKey == null || propertyKey.trim().length() == 0) {
			throw new IllegalArgumentException ("Illegal property");
		}
		if (props.containsKey(propertyKey.trim())) {
			return props.getProperty(propertyKey).trim();
		} else {
			throw new NoSuchPropertyException(
					"Do not have property with key "+ propertyKey + "in "
					+ propertyFile);
		}
	}

}
